package com.zlsy.secondtime.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * @author zhouliang
 * @date 2020/5/17 16:13
 * <p>
 * 两个线程交替打印0~100的奇偶数，用synchronized关键字实现。
 */
public class WaitNotifyPrintOddEvenSync {

    private static int count;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    //当两个99都阻塞到这里的时候，必然总有一次（(count & 1) == 1）能抢到锁
                    //然后执行完 count++;，并且释放锁，于是这里拿到锁进去后count变成100
                    //打印100 ，count++,释放锁，程序结束。
                    synchronized (lock) {
                        if ((count & 1) == 0) {
                            System.out.println("偶数线程打印出：" + count);
                            count++;
                        }
                    }
                }
            }
        });

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    synchronized (lock) {
                        if ((count & 1) == 1) {
                            System.out.println("奇数线程打印:" + count);
                            count++;
                        }
                    }
                }
            }
        });

        thread.start();
        thread1.start();
    }
}
